component extends="com.firemoss.atonement.example.contactmanager.service.remote.AbstractRemotingFacade"
{
	import com.firemoss.atonement.example.contactmanager.service.dto.*;
	import com.firemoss.atonement.example.contactmanager.model.*;

	private function getService()
	{
		return getBean( "contactManagerService" );
	}
	
	private function getMapper()
	{
		return getBean( "mapper" );
	}

	remote function getCompany( id )
	{
		return getMapper().map( getService().getCompany( id ), createObject( "component", "com.firemoss.atonement.example.contactmanager.service.dto.CompanyDTO") );
	}
	
	remote function getContact( id )
	{
		return getMapper().map( getService().getContact( id ), createObject( "component", "com.firemoss.atonement.example.contactmanager.service.dto.ContactDTO") );
	}
	
	remote function listCompanies()
	{
		return getMapper().mapArray( getService().listCompanies(), "com.firemoss.atonement.example.contactmanager.service.dto.CompanyDTO" );
	}
	
	remote function listContacts()
	{
		return getMapper().mapArray( getService().listContacts(), "com.firemoss.atonement.example.contactmanager.service.dto.ContactDTO" );
	}
	
	remote function saveCompany( companyDto )
	{
		if ( not isNull( companyDto.getId() ) )
		{
			var company = getService().getContact( companyDto.getId() );
		}
		if ( isNull( company ))
		{
			companyDto.setId( 0 );
			var company = createObject( "component", "com.firemoss.atonement.example.contactmanager.model.Company" );
		}
		
		getMapper().map( companyDto, company );
		getService().saveCompany( company );
		
		var result = getMapper().map( company, createObject( "component", "com.firemoss.atonement.example.contactmanager.service.dto.CompanyDTO") );
		
		return result;
	}
	
	remote function saveContact( contactDto )
	{
		if ( not isNull( contactDto.getId() ) )
		{
			var contact = getService().getContact( contactDto.getId() );
		}
		
		if ( isNull( contact ))
		{
			contactDto.setId( 0 );
			var contact = createObject( "component", "com.firemoss.atonement.example.contactmanager.model.Contact" );
		}
		
		getMapper().map( contactDto, contact );
		getService().saveContact( contact );
		var result = getMapper().map( contact, createObject( "component", "com.firemoss.atonement.example.contactmanager.service.dto.ContactDTO") );
		
		return result;
	}
	
	// Used in assembly
	
	public function resolveCompanyId( source, targetProperty, mapping, mappingChain ) {
		if ( not isNull( source.getCompany() ) )
		{
			writeLog("resolveCompanyId: #source.getCompany().getId()#");
			return source.getCompany().getId();
		}
		else
		{
			return 0;
		}
	} 
	
	public function resolveCompany( source, targetProperty, mapping, mappingChain ) {
		if ( not isNull( source ) )
		{
			return getService().getCompany( source );
		}
	} 
	
}
